<template>
  <a-modal
    title="编辑权限"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="唯一识别码"
        >
          <a-input placeholder="唯一识别码" v-decorator="['code', {rules: [{required: true, message: '唯一识别码不能为空！'}]}]" />
        </a-form-item> -->
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色名称">
          <a-input
            placeholder="角色名称"
            v-decorator="['name', { rules: [{ required: true, message: '角色名称不能为空！' }] }]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
          <a-select
            placeholder="状态"
            v-decorator="['status', { rules: [{ required: true, message: '状态不能为空！' }] }]"
          >
            <a-select-option value="1">正常</a-select-option>
            <a-select-option value="2">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="描述" hasFeedback>
          <a-textarea :rows="3" placeholder="描述" v-decorator="['description']" />
        </a-form-item>
        <!-- <a-divider /> -->
        <a-tabs default-active-key="1" @change="callback">
          <a-tab-pane key="1" tab="拥有权限">
            <a-form-item label="拥有权限" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-row :gutter="16" v-for="(permission, index) in tAllAuthorities" :key="index">
                <a-col :xl="5" :lg="24"> {{ permission.name }}： </a-col>
                <a-col :xl="19" :lg="24">
                  <a-checkbox
                    v-if="permission.actions.length > 0"
                    :indeterminate="permission.indeterminate"
                    :checked="permission.checkedAll"
                    @change="onChangeCheckAll($event, permission)"
                  >
                    全选
                  </a-checkbox>
                  <a-checkbox-group
                    :options="permission.actionsFormat"
                    v-model="permission.selected"
                    @change="onChangeCheck(permission)"
                  />
                </a-col>
              </a-row>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane key="2" tab="菜单配置" force-render>
            <a-form-item label="菜单配置" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-tree
                v-model="checkedKeys"
                :selected-keys="selectedKeys"
                checkable
                :tree-data="tAllMenusList"
                @select="onSelect"
                @check="onCheck"
              >
              </a-tree>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane key="3" tab="接口权限">
            <a-spin :spinning="loading">
              <a-table
                v-model="selectedRowKeys"
                ref="table"
                :columns="columns"
                :rowSelection="rowSelection"
                :dataSource="tAllInterface"
                :pagination="pagination"
                @change="handleTableChange"
                rowKey="svcCode"
              >
              </a-table>
            </a-spin>
          </a-tab-pane>
          <a-tab-pane key="4" tab="业务权限" force-render>
            <a-form-item label="配置业务" :labelCol="labelCol" :wrapperCol="wrapperCol" class="category-list">
              <a-checkbox-group @change="onChangeCategory" v-model="categoryChecked">
                <a-row>
                  <a-col :span="24" v-for="(item, index) in categoryList" :key="index">
                    <a-checkbox :value="item.id" :checked="true"> {{ item.title }}({{ item.alias }}) </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { editRoles, editRoleAuthorities, editRoleMenus, editRoleServices, getTInterfaceManageList } from '@/api/role'
import { sqlSelect, sqlUpdate } from '@/api/sql'
export default {
  name: 'EditModal',
  data () {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      confirmLoading: false,
      tAllInterface: [],
      mdl: {},
      update_time: '2020-04-28 07:02:00',
      roles: [],
      treeData: [],
      checkedKeys: [],
      selectedKeys: [],
      selectedRowKeys: [], // 添加这个属性, 也就是他管理着选中行
      // selectedRowKeys: ['CS1355011', 'CS1355021', 'CS1455011', 'CS1455021'],
      record: {},
      // rowSelection: {
      //   selectedRowKeys: [],
      //   onChange: this.onSelectChange
      // },
      columns: [
        {
          title: '接口号',
          width: 100,
          dataIndex: 'svcCode',
          key: 'svcCode',
          scopedSlots: { customRender: 'svcCode' },
          sorter: (a, b) => {
            return a.svcCode.localeCompare(b.svcCode)
          } // 排序设置
        },
        {
          title: '接口别名',
          dataIndex: 'shortName',
          key: 'shortName'
        },
        {
          title: '接口简称',
          dataIndex: 'name',
          key: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '源系统',
          dataIndex: 'tSystemSource.name'
        },
        {
          title: '目标系统',
          dataIndex: 'tSystemTarget.name'
        },
        // {
        //   title: '接口重发Link',
        //   dataIndex: 'contact_tele',
        //   scopedSlots: { customRender: 'contact_tele' }
        // },
        {
          title: '注册日期',
          dataIndex: 'crt_time',
          scopedSlots: { customRender: 'crt_time' }
        }
      ],
      loading: true,
      // permission: {
      //   selected: [ 'add', 'get', 'details', 'update' ]
      // },
      // 向后端拉取可以用的操作列表
      permissionList: [
        { label: '新增', value: 'add', defaultChecked: false },
        { label: '查询', value: 'get', defaultChecked: false },
        { label: '修改', value: 'update', defaultChecked: false },
        { label: '详情', value: 'details', defaultChecked: false },
        { label: '列表', value: 'query', defaultChecked: false },
        { label: '删除', value: 'delete', defaultChecked: false },
        { label: '导入', value: 'import', defaultChecked: false },
        { label: '导出', value: 'export', defaultChecked: false }
      ],
      // 分页属性
      pagination: {
        defaultPageSize: 10,
        pageNo: 0,
        pageSize: 10, // 默认每页显示数量
        showSizeChanger: true, // 显示可改变每页数量
        showQuickJumper: true, // 是否可以快速跳转至某页
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: (total) => this.$t('pagination.Total') + ` ${total} ` + this.$t('pagination.items'), // 分页中显示总的数据
        total: 0 // 总条数
      },
      form: this.$form.createForm(this),
      categoryList: [], // 业务列表
      categoryChecked: [] // 选择的业务
    }
  },
  // 父组件传递菜单/权限
  props: {
    tAllMenusList: {
      type: Array,
      default: null
    },
    tAllAuthorities: {
      type: Array,
      default: null
    }
  },
  created () {
    // this.getAllPermissionList()
    // this.getAllMenusList()
  },
  async mounted () {
    // this.getTInterfaceManageList()
    // this.rowSelection()
    this.categoryList = await this.getCategoryList()
    console.log('this.categoryList', this.categoryList)
  },
  computed: {
    rowSelection () {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: this.onSelectChange
        // hideDefaultSelections: false,
        // selections: true
        // type: 'radio'
      }
    }
  },
  methods: {
    // 列表选中事件
    onSelectChange (selectedRowKeys) {
      console.log('selectedRowKeys changed: -------------', selectedRowKeys)
      // 去重 Array.from(new Set(arr))
      this.rowSelection.selectedRowKeys = Array.from(new Set(selectedRowKeys))
      this.selectedRowKeys = selectedRowKeys
    },
    callback (key) {
      console.log(key)
    },
    onChangeCheck (permission) {
      // console.log('permission------:', permission)
      // console.log(permission.selected.length)
      permission.indeterminate = !!permission.selected.length && permission.selected.length < permission.actions.length
      permission.checkedAll = permission.selected.length === permission.actions.length
    },
    onChangeCheckAll (e, permission) {
      // console.log('permission:', permission)
      Object.assign(permission, {
        selected: e.target.checked ? permission.actions.map((obj) => obj) : [],
        indeterminate: false,
        checkedAll: e.target.checked
      })
    },
    onSelect (selectedKeys, info) {
      // console.log('selected', selectedKeys, info)
      this.selectedKeys = selectedKeys
    },
    onCheck (checkedKeys, info) {
      // console.log('选中菜单节点-----', checkedKeys, info)
      this.checkedKeys = checkedKeys
    },
    // 选中创建时间
    createdChange (value, dateString) {
      // console.log('Formatted Selected Time: ', dateString)
    },
    // 选中创建时间
    updateChange (value, dateString) {
      // console.log('Formatted Selected Time: ', dateString)
    },
    compareToFirstPassword (rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        // callback('Two passwords that you enter is inconsistent!')
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    },
    validateToNextPassword (rule, value, callback) {
      const form = this.form
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },
    // 获取接口列表
    getTInterfaceManageList () {
      const filter = { sort: 'id,asc', page: this.pagination.pageNo, size: this.pagination.pageSize }
      getTInterfaceManageList(filter)
        .then((response) => {
          response.data.forEach((item) => {
            item.crt_time = moment(item.crt_time).format('YYYY-MM-DD HH:mm:ss')
          })
          this.loading = false
          this.pagination.total = Number(response.totalCount)
          this.tAllInterface = response.data
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 分页方法
    handleTableChange (pagination) {
      // this.pagination.current = pagination.current
      this.pagination.pageNo = pagination.current - 1
      this.pagination.pageSize = pagination.pageSize
      this.getTInterfaceManageList()
    },
    edit (record) {
      this.record = record
      this.mdl = Object.assign({}, record)
      const selectAuthority = JSON.parse(record.tRoleMenuAuthority.authority)
      // const authority = record.tRoleMenuAuthority.authority
      // 有权限表，处理勾选
      if (this.mdl.tRoleMenuAuthority && this.tAllAuthorities) {
        // // 先处理要勾选的权限结构
        const permissionsAction = {}
        selectAuthority.map((entity) => {
          permissionsAction[entity.code] = entity.permission
        })

        var b
        clearTimeout(b)
        const _that = this
        b = setTimeout(function () {
          console.log('延迟一下')
          _that.tAllAuthorities.forEach((permission) => {
            const selected = permissionsAction[permission.code]
            permission.selected = selected || []
            permission.aaa = '88888'
            _that.onChangeCheck(permission)
          })

          // 选择的业务权限
          _that.categoryChecked = record.tRoleCategory.category.split(',')
          // 字符串转数字
          _that.categoryChecked = _that.categoryChecked.map((item) => Number(item))
          console.log('this.record', this.record)
        }, 700)

        console.log('this.tAllAuthorities', this.tAllAuthorities)
        // console.log('this.permissions', this.permissions)
      }
      var t
      clearTimeout(t)
      const _that = this
      t = setTimeout(function () {
        _that.checkedKeys = _that.mdl.tRoleMenu.menu.split(',').map(Number)
        console.log('打印处理后的菜单-----', _that.checkedKeys)
      }, 700)

      // console.log('编辑详情--------------', record)
      if (record) {
        // ...省略我的业务逻辑
        const troleService = record.tRoleService ? record.tRoleService.service.split(',') : []
        const selectedRowKeys = (troleService.length > 0 && troleService) || []
        this.selectedRowKeys = selectedRowKeys
      } else {
      }

      this.visible = true
      const {
        form: { setFieldsValue }
      } = this
      this.$nextTick(() => {
        setFieldsValue({
          id: this.mdl.id,
          // code: this.mdl.code,
          name: this.mdl.name,
          status: this.mdl.status,
          actions: this.mdl.actions,
          description: this.mdl.description
        })
      })
    },
    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        console.log('errors:', errors, 'val:', values)
        values.id = this.mdl.id
        // 提取想要的对象组成新数组对象
        const tRoleMenuAuthority = []
        this.tAllAuthorities.forEach(function (item) {
          tRoleMenuAuthority.push({ name: item.name, code: item.code, permission: item.selected })
        })

        const filter = { id: this.mdl.tRoleMenuAuthority.id, authority: JSON.stringify(tRoleMenuAuthority) }
        editRoleAuthorities(filter).then((authority) => {
          const filtermenu = { id: this.mdl.tRoleMenu.id, menu: this.checkedKeys.join(',') }
          // 角色菜单
          editRoleMenus(filtermenu).then((rolemenu) => {
            const filterServices = { id: this.mdl.tRoleService.id, service: this.selectedRowKeys.join(',') }
            editRoleServices(filterServices).then((roleServices) => {
              console.log(this.categoryChecked, this.record)
              // 添加业务
              this.updateRoleCategory(this.categoryChecked, this.record.tRoleCategory.id).then((roleCategory) => {
                if (!errors) {
                  values.tRoleMenuAuthority = authority
                  values.tRoleMenu = rolemenu
                  values.tRoleService = roleServices
                  values.interface_id = 1
                  values.create_by = this.mdl.create_by
                  values.createDate = moment.utc(this.mdl.createDate)
                  values.update_by = this.mdl.update_by
                  values.update_date = this.mdl.update_date
                  values.tRoleCategory = roleCategory
                  editRoles(values).then((res) => {
                    if (res) {
                      // 存储成功、刷新列表
                      this.$emit('ok', values)
                      this.visible = false
                      this.confirmLoading = false
                      this.$notification['success']({
                        message: '提示',
                        description: '数据修改成功！'
                      })
                    }
                  })
                } else {
                  this.confirmLoading = false
                }
              })
            })
          })
        })
      })
    },
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
    },

    /**
     * 获取业务列表
     */
    getCategoryList () {
      const params = {
        sql: `select * from t_category`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /**
     * 选择业务
     */
    onChangeCategory (checkedValues) {
      console.log('选择的业务 = ', checkedValues)
      this.categoryChecked = checkedValues
    },

    /**
     * 提交选择的业务
     */
    updateRoleCategory (values, id) {
      console.log(values, id)
      var params = {
        sql: `update t_role_category set category='${values}' where id=${id}`
      }
      return new Promise((resolve, reject) => {
        sqlUpdate(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    }
  }
}
</script>
